<?php
require_once 'modules/consumer/models/Consumer.php';
require_once 'modules/user/models/User.php';
require_once 'modules/mail/models/Mail.php';
require_once 'modules/list/models/List.php';
require_once 'modules/user/models/Wallet.php';

class consumer_ProfileController extends Nine_Controller_Action
{
	public $userId;
	
	public function registerAction()
	{
		$this->view->headTitle ( Nine_Language::translate('Register Consumer') );
		$this->view->menuId = 'consumer';
		
		$objUser = new Models_User ();
		$objConsumer = new Models_Consumer();
		$objList = new Models_List();
		
		$data = $this->_getParam ( 'data', false );
		
		$errors = array();
		if (false != $data) {
			
			if (null != $_SESSION['captcha'] && $_SESSION['captcha'] == strtoupper(@$data['captcha'])) {
				
				/**
				 * Generate activation code
				 */
				$activationCode = $objUser->generateActiveCode();
				/**
				 * Insert new user
				 */
				$newUser = array(
	                            'group_id'        => 3,
	            				'full_name'		  => $data['full_name'],
	                            'username'        => $data['username'],
	            				'password'        => $data['password'],
	                            'repeat_password' => $data['retype_password'],
	                            'email'           => $data['email'],
	            				'created_date'    => time(),
	                            'enabled'         => 1,
								'active_code'	  => $activationCode
	                        );
	            $errors = $objUser->validate($newUser);
	            if (true === $errors) {
	                $newUser['password'] = md5($newUser['password']);
	                /**
	                 * TODO Read date format from language table
	                 */
	                unset($newUser['repeat_password']);
	                unset($newUser['repeat_email']);
	                try {
	                	
	                    $id = $objUser->insert($newUser);
	                    $bd = explode("/", trim($data['birthday']));
	                    $newConsumer = array(
	                    					'consumer_id' => $id,
	                                        'user_id'    => $id,
	                    					'authentication_type' => @$data['authentication_type'],
	                    					'telephone_no' => @$data['telephone_no'],
	                    					'birthday' => mktime(0,0,0,@$bd[1],@$bd[0],@$bd[2]),
	                    					'gender' => @$data['gender'],
	                    					'address' => @$data['address'],
	                    					'postcode' => @$data['postcode'],
	                    					'city' => @$data['city'],
	                    					'nation' => @$data['nation'],
	                    					'ssn' => @$data['ssn'],
	                   						'approved' => 0,
	                                    );
	                    if (null != @$newConsumer['telephone_no']) {
	                    	$newConsumer['telephone_no'] = "+84" . substr($newConsumer['telephone_no'], 1, strlen($newConsumer['telephone_no'])-1);
	                    }
	                                   
	                                    
	                    $objConsumer->insert($newConsumer);
	                    /**
	                     * Send email registration successfully
	                     */
	                    $objMail = new Models_Mail();
	                    $mailValues = array(
	                    				'username'	=>	$newUser['username'],
	                    				'fullname'	=>	$newUser['full_name'],
	                    				'email'		=>	$newUser['email'],
	                    				'activationcode' => $newUser['active_code']
	                    			);
	                    $objMail->sendHtmlMail('register_user',$mailValues,$newUser['email']);
	                    			
	                    $this->auth->loginAuto($newUser['username']);
		                $this->_redirect("consumer/profile/activate");
		                
	                } catch (Exception $e) {
	                	unset($_SESSION['captcha']);
						$errors = array('main' => Nine_Language::translate('Can not insert into database now'));
	                }
	            }
			} 
			else {
				$this->session->__unset('captcha');
				$errors = array('main' => Nine_Language::translate('Code is not match. Please type again'));
			}
		}
		
		$this->view->data = $data;
		$this->view->allProvinces = $objList->getLists(1);
		$this->view->randomNumber = rand(0, 1000000);
		$this->view->errors = $errors;
	}
	
	public function activateAction(){
		$this->view->headTitle ( Nine_Language::translate('Activate Consumer') );
		$this->view->menuId = 'consumer';
		
		$data = $this->_getParam ( 'data', false );
		$error = array();
		if (false != $data) {
			$user = @Nine_Registry::getLoggedInUser()->toArray();
			if (trim($data['activation_code']) == $user['active_code']) {
				/**
				 * Activate user
				 */
				$objConsumer = new Models_Consumer();
				$objConsumer->update(array('approved' => 1), array('user_id=?' => Nine_Registry::getLoggedInUserId()));	
				
				/**
				 * Send email confirm finish account
				 */
				$objMail = new Models_Mail();
	            $mailValues = array(
                    		'username'	=>	$user['username'],
                    		'fullname'	=>	$user['full_name'],
                    		'email'		=>	$user['email'],
	                    	);
	             $objMail->sendHtmlMail('finish_register',$mailValues,$user['email']);
				
				
				
				$this->_redirect("consumer/profile/finish");
			}
			else {
				$error = array(
							'main' => Nine_Language::translate("Activation code is not valid. Please try again !")
						);
			}
		}
		$this->view->error = $error;
		$this->view->data = $data;
	}
	
	
	/**
	 * Finish
	 */
	public function finishAction(){
		$this->view->headTitle ( Nine_Language::translate('Finish Consumer') );
		$this->view->menuId = 'consumer';
		
		$data = $this->_getParam ( 'data', false );
		$error = array();
		if (false != $data) {
			
//			if (null != @$data['credit_number'] && null != @$data['credit_code'] ) {
				$objWallet = new Models_Wallet();
				/**
				 * Check unique credit
				 */
//				if (false != $objWallet->checkUniqueCreditID($data['credit_number'])) {
					
					/**
					 * Create wallet
					 */
					
					$newWallet = array(
									'user_id' => Nine_Registry::getLoggedInUserId(),
									'credit_number' => @trim($data['credit_number']),
									'credit_code' => @trim($data['credit_code']),
									'value' => 1000
									);
					$objWallet->insert($newWallet);
					
					/**
					 * Send email congratulation
					 */
					$objMail = new Models_Mail();
					$user = @Nine_Registry::getLoggedInUser()->toArray();
		            $mailValues = array(
	                    		'username'	=>	$user['username'],
	                    		'fullname'	=>	$user['full_name'],
	                    		'email'		=>	$user['email'],
	                    	);
	            	 $objMail->sendHtmlMail('welcome_new_user',$mailValues,$user['email']);
					
					
					$this->session->registerMessage = array(
		                                               'success' => true,
		                                               'message' => Nine_Language::translate('Register Consumer is finished. You can use it now !')
		                                           );
					/**
					 * Redirect to manager
					 */
					$this->_redirect('consumer');
					
//				}
//				else {
//					$error = array(
//							'main' => Nine_Language::translate("Credit is used. Please choose other credit")
//							);
//				}
				
//			}
//			else {
//				$error = array(
//							'main' => Nine_Language::translate("Please enter valid credit card number.")
//							);
//			}
		}
		$this->view->error = $error;
		$this->view->data = $data;
	}
	
	public function viewAction()
	{
		$this->view->headTitle ( Nine_Language::translate('View Consumer Profile') );
		$this->view->menuId = 'consumer';
		
		$this->_checkLogin();
		
		$objUser = new Models_User();
		$objList = new Models_List();
		
		$currentUser = $objUser->getUserWithConsumerProfile($this->userId);
		
		if (null != @$currentUser['birthday']) {
			$currentUser['birthday'] = date(Nine_Registry::getConfig('dateFormat'),$currentUser['birthday']);
		}
		
		$this->view->currentUser = $currentUser;
		$this->view->allProvinces = $objList->getLists(1);
		$this->view->randomNumber = rand(0, 1000000);
	}
	
	
	private function _checkLogin()
	{
		if (null != @Nine_Registry::getLoggedInUser()) {
			$this->userId = Nine_Registry::getLoggedInUserId();
		}
		else {
			$this->_redirect("access/index/login");
		}
	}
	
}